package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.xiyi.shouxin.dao.user.QuestionRepository;
import com.xiyi.shouxin.dao.user.UserAnswerRepository;
import com.xiyi.shouxin.dao.user.UserRepository;
import com.xiyi.shouxin.entity.user.Question;
import com.xiyi.shouxin.entity.user.User;
import com.xiyi.shouxin.entity.user.UserAnswer;
import com.xiyi.shouxin.entity.user.mapper.QuestionMapper;
import com.xiyi.shouxin.entity.user.mapper.UserMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.global.QuestionEnum;
import com.xiyi.shouxin.view.pojo.AnswerView;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.QuestionView;
import com.xiyi.shouxin.view.pojo.UserAnswerView;
import com.xiyi.shouxin.view.pojo.UserView;

@Service
public class QuestionService {
    private Gson gson = new Gson();
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private UserAnswerRepository userAnswerRepository;
    @Autowired
    private UserRepository userRepository;

    /*
     * 问题列表
     */
    public ItemPage<QuestionView> findQuestionList(Integer status, int page, int size) throws Exception {
        List<QuestionView> list = new ArrayList<>();
        List<Question> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");

        result = questionRepository.findByMultiConditionsByPage(status, sort, page, size);
        total = questionRepository.countByMultiConditions(status);

        for (Question question : result) {
            list.add(new QuestionView(question));
        }
        return new ItemPage<QuestionView>(list, total);
    }

    /*
     * 问题详情
     */
    public QuestionView findQuestionInfo(Long id) throws Exception {
        Question question = questionRepository.findById(id, new QuestionMapper());
        if (question == null) {
            return null;
        }
        return new QuestionView(question);
    }

    /*
     * 新增问题
     */
    public QuestionView createQuestion(Question question) throws Exception {
        if (question == null || !StringUtils.hasText(question.getTitle())) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        // 检查类型和参数
        if (question.getType() == null || (!QuestionEnum.CHECKBOX.getType().equals(question.getType())
                && !QuestionEnum.RADIO.getType().equals(question.getType())
                && !QuestionEnum.INPUT.getType().equals(question.getType()))) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }

        Long id = questionRepository.create(question);
        question.setId(id);
        return new QuestionView(question);
    }

    /*
     * 修改问题
     */
    public void updateQuestion(Question question) throws Exception {
        if (question == null || question.getId() == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        // 检查类型和参数
        if (question.getType() != null && (!QuestionEnum.CHECKBOX.getType().equals(question.getType())
                && !QuestionEnum.RADIO.getType().equals(question.getType())
                && !QuestionEnum.INPUT.getType().equals(question.getType()))) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        questionRepository.update(question.getId(), question);
    }

    /*
     * 删除问题
     */
    public void delQuestion(List<Long> ids) throws Exception {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        questionRepository.delByIds(ids);
    }

    /*
     * 查询用户问题回答
     */
    public UserAnswerView findUserAnswer(Long userId) throws Exception {
        if (userId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        User user = userRepository.findById(userId, new UserMapper());
        if (user == null) {
            throw new CommonException(ErrorCode.NOTFOUND);
        }
        UserAnswer userAnswer = userAnswerRepository.findFirstByUid(userId);
        List<AnswerView> answers = new ArrayList<>();
        if (userAnswer != null && StringUtils.hasText(userAnswer.getAnswer())) {
            HashMap<String, String> an = gson.fromJson(userAnswer.getAnswer(), HashMap.class);
            for (String qId : an.keySet()) {
                Question question = questionRepository.findById(Long.valueOf(qId), new QuestionMapper());
                answers.add(new AnswerView(new QuestionView(question), an.get(qId)));
            }
        }
        return new UserAnswerView(new UserView(user, null,null), answers);
    }

    /*
     * 用户回答列表
     */
    public ItemPage<UserAnswerView> findAnswerList(String keyword, int page, int size) throws Exception {
        List<UserAnswerView> list = new ArrayList<>();
        List<User> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");

        result = userRepository.findByMultiConditionsByPage(null,keyword, null, null, sort, page, size);
        total = userRepository.countByMultiConditions(null,keyword, null, null);

        for (User user : result) {
            UserAnswer userAnswer = userAnswerRepository.findFirstByUid(user.getId());
            List<AnswerView> answers = new ArrayList<>();
            if (userAnswer != null && StringUtils.hasText(userAnswer.getAnswer())) {
                HashMap<String, String> an = gson.fromJson(userAnswer.getAnswer(), HashMap.class);
                for (String qId : an.keySet()) {
                    Question question = questionRepository.findById(Long.valueOf(qId), new QuestionMapper());
                    answers.add(new AnswerView(new QuestionView(question), an.get(qId)));
                }
            }
            list.add(new UserAnswerView(new UserView(user, null,null), answers));
        }
        return new ItemPage<UserAnswerView>(list, total);
    }

    @Transactional(rollbackFor =Exception.class )
    public void answerQuestion(Long uid, String answer) throws Exception {
        User user = userRepository.findById(uid, new UserMapper());
        if (user == null) {
            throw new CommonException(ErrorCode.NOTFOUND);
        }
        if (user.getIsAnswer() != null && user.getIsAnswer() == 1) {
            throw new CommonException(ErrorCode.ALREADYANSWER);
        }
        UserAnswer ua = new UserAnswer();
        ua.setUid(uid);
        ua.setAnswer(answer);
        userAnswerRepository.create(ua);
        user.setIsAnswer(1);
        userRepository.update(uid, user);
    }

}
